

package com.hazelcast.instance.impl;

import com.hazelcast.core.HazelcastInstanceAware;
import com.hazelcast.core.ManagedContext;
import com.hazelcast.internal.serialization.SerializationServiceAware;
import com.hazelcast.internal.services.NodeAware;

public final class HazelcastManagedContext implements ManagedContext {

    private final HazelcastInstanceImpl instance;
    private final ManagedContext externalContext;
    private final boolean hasExternalContext;

    public HazelcastManagedContext(HazelcastInstanceImpl instance, ManagedContext externalContext) {
        this.instance = instance;
        this.externalContext = externalContext;
        this.hasExternalContext = externalContext != null;
    }

    @Override
    public Object initialize(Object obj) {
        if (obj instanceof HazelcastInstanceAware aware) {
            aware.setHazelcastInstance(instance);
        }
        if (obj instanceof NodeAware aware) {
            aware.setNode(instance.node);
        }
        if (obj instanceof SerializationServiceAware aware) {
            aware.setSerializationService(instance.node.getSerializationService());
        }

        if (hasExternalContext) {
            return externalContext.initialize(obj);
        }
        return obj;
    }
}
